package org.example;

import redis.clients.jedis.Jedis;

import java.util.Random;

/**
 * @DESCRIPTION: 模拟发送手机验证码
 * @USER: shg
 * @DATE: 2022/11/5 20:12
 */
public class PhoneCode {

    public static void main(String[] args) {
        String phoneNum = "18170628926";

        sendVerifyCode(phoneNum);

        // 3. 校验验证码
        // verifyCode(phoneNum,"76259");

    }

    private static void verifyCode(String phoneNum,String code) {
        Jedis jedis = new Jedis("192.168.11.131", 6379);
        //验证码key
        String codeKey = "VerifyCode_"+phoneNum+":code";
        String redisCode = jedis.get(codeKey);

        // 判断验证码是否一致
        if(redisCode.equals(code)){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
        jedis.close();
    }

    // 每个手机每天只能发送三次，验证码放到redis中，设置过期时间120
    private static void sendVerifyCode(String phone){
        Jedis jedis = new Jedis("192.168.11.131", 6379);

        String codeKey = "VerifyCode_"+phone+":code";
        String countKey = "VerifyCode_"+phone+":count";

        String count = jedis.get(countKey);
        if(count == null){
            jedis.setex(countKey, 24*60*60, "1");
        }else if(Integer.parseInt(count) <= 2) {
            jedis.incr(countKey);
        } else if (Integer.parseInt(count) > 2) {
            System.out.println("24小时内最多发送三次验证码");
            jedis.close();
            return;
        }

        // 发送验证码到redis中
        String code = getRandomCode();
        jedis.setex(codeKey, 120,code);
        jedis.close();
    }
    // 1. 生成随机6位验证码
    private static String getRandomCode() {

        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0;i<6;i++){
            Random random = new Random();
            int num = random.nextInt(10);
            stringBuilder.append(num);
        }
        return stringBuilder.toString();
    }
}
